package com.kuang;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kuang.mapper.BlogCategoryMapper;
import com.kuang.service.BlogCategoryService;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@SpringBootApplication
@MapperScan("com.kuang.mapper")
public class KuangstudyApplication implements CommandLineRunner {

	@Autowired
	BlogCategoryService blogCategoryService;
	@Autowired
	SqlSessionTemplate sqlSessionTemplate;
	public static void main(String[] args) {
		SpringApplication.run(KuangstudyApplication.class, args);
	}
	List<String> ob_list = new ArrayList<>();
	//需要新增的字段

	List<String[]> add_list = new ArrayList<>();

	//数据库缺少的字段
	List<String[]> resultList = new ArrayList<>();
	@Override
	public void run(String... args) throws Exception {
//		System.out.println("执行");
//		QueryWrapper queryWrapper = new QueryWrapper();
//		queryWrapper.select("show columns from ks_blog_category");
//		Map map = blogCategoryService.getMap(queryWrapper);
//		System.out.println(map);
		add_list.add(new String[]{"f_volume_dry","1"}); //体积干
		add_list.add(new String[]{"f_volume_wet","体积干"}); //体积湿
		add_list.add(new String[]{"f_quality_dry","质量干"}); //质量干
		add_list.add(new String[]{"f_quality_wet","质量湿"}); //质量湿
		String sql = "show columns from ks_blog_category";
		SqlSession sqlSession = openSession();
		PreparedStatement preparedStatement = sqlSession.getConnection().prepareStatement(sql);
		ResultSet resultSet = preparedStatement.executeQuery();
		while (resultSet.next()){
			ob_list.add(resultSet.getString(1));
		}

		for (String[] item : add_list) {  //获取表中不存在的字段
			if (!ob_list.contains(item[0])) {
				resultList.add(item);
				System.out.println("缺少的的字段"+item[0]);
			}
		}

		String add_sql= "";
		for (String[] strings : resultList) {

			add_sql = "alter table ks_blog_category add "+strings[0]+ " varchar(18) comment '"+strings[1]+"'";
			try {
				System.out.println("执行的sql"+add_sql);
				sqlSession.getConnection().prepareStatement(add_sql).execute();
			}catch (Exception e){
				e.printStackTrace();
			}

		}
		closeSession(sqlSession);



	}



	private SqlSession openSession() {
		SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
		return sqlSessionFactory.openSession();
	}

	//    关闭链接
	private void closeSession(SqlSession sqlSession) {
		sqlSession.close();
	}

}